package com.zhouwr.simulator;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 *
 */
@Slf4j
public class NettyClient {
    private final String remoteHost;
    private final int localPort;
    private final int remotePort;

    private NettyClientHandler mClientHandler;

    private ChannelFuture mChannelFuture;

    /**
     * Instantiates a new Netty client.
     *
     * @param remoteHost the remote host
     * @param remotePort the remote port
     * @param localPort  the local port
     */
    public NettyClient(String remoteHost, int remotePort, int localPort) {
        this.remoteHost = remoteHost;
        this.localPort = localPort;
        this.remotePort = remotePort;
    }

    /**
     * Connect.
     */
    public void connect() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            mClientHandler = new NettyClientHandler();
            b.group(workerGroup).channel(NioSocketChannel.class)
                    .localAddress(localPort)
                    // KeepAlive
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    // Handler
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new IdleStateHandler(5, 5, 10));
                            channel.pipeline().addLast("logging", new LoggingHandler(LogLevel.INFO));
                            channel.pipeline().addLast(
                                    new DelimiterBasedFrameDecoder(1024,
                                    Unpooled.copiedBuffer(new byte[] { 0x7e }),
                                    Unpooled.copiedBuffer(new byte[] { 0x7e }))
                            );

                            channel.pipeline().addLast(new ByteArrayDecoder());
                            channel.pipeline().addLast(new ByteArrayEncoder());
                            channel.pipeline().addLast(mClientHandler);
                        }
                    });
            mChannelFuture = b.connect(remoteHost, remotePort).sync();
            if (mChannelFuture.isSuccess()) {
                log.info("Client,连接服务端成功");
            }
            mChannelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
